//202102104015柴亚楠
package cn.edu.sdjzu.xg.kcsj.controller;

import cn.edu.sdjzu.xg.kcsj.domain.Classroom;
import cn.edu.sdjzu.xg.kcsj.service.ClassroomService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/deleteClassroom.ctl")
public class DeleteClassroomController extends HttpServlet {
    @Override
    protected void doGet (HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        JSONObject respMessage = new JSONObject ();
        String id_str = req.getParameter ("id");
        if (id_str == null){
            respMessage.put ("message","no have request");
        }else {
            int id = Integer.parseInt (id_str);
            try {
                if (ClassroomService.getInstance().delete(id)){
                    respMessage.put ("message","delete yes");
                }else {
                    respMessage.put ("message","delete no");
                }
            } catch (SQLException e ) {
                e.printStackTrace ();
                respMessage.put ("message","sql have exception!");
            }
        }
        resp.getWriter ().println (respMessage);
    }

    @Override
    protected void doPost (HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        JSONObject respMessage = new JSONObject();
        String request_json= JSONUtil.getJSON(req);
        JSONObject req_jsonObj = JSON.parseObject(request_json);
        JSONArray List_jsonArray = req_jsonObj.getJSONArray("ListToDelete");
        List<Classroom> listToDelete = null;
        listToDelete= List_jsonArray.toJavaList(Classroom.class);
        try {
            if (ClassroomService.getInstance().deletes(listToDelete)){
                respMessage.put("message", "deletes yes");
            }else {
                respMessage.put("message", "have other relationships");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace ();
            respMessage.put("message", "have other relationships");
        }
        resp.getWriter ().println (respMessage);
    }

}
